package OptimalAlgorithm.String;
//https://leetcode.cn/problems/longest-common-prefix/description/
public class LongestCommonPrefix {
/*(方法一：两两比较)    public String longestCommonPrefix(String[] strs) {
        String str = strs[0];
        for (int i = 0; i < strs.length; i++) {
            if(i + 1 != strs.length){
                str = cmp(str,strs[i + 1]);
            }
        }
        return str;
    }
    private String cmp(String s1, String s2){
        int len = 0;
        for (int i = 0; i < s1.length(); i++) {
            if(i >= s2.length()){
                break;
            }
            if (s1.charAt(i) == s2.charAt(i)){
                len++;
            }else{
                break;
            }
        }
        if (len == 0){
            return "";
        }
        return s1.substring(0,len);
    }*/
    //方法二：统一比较
    public String longestCommonPrefix(String[] strs) {
        for (int i = 0; i < strs[0].length(); i++) {
            for (int j = 1; j < strs.length; j++) {
                if(i == strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)){
                    return strs[0].substring(0,i);
                }
            }
        }
        return strs[0];
    }

//    public static void main(String[] args) {
//        String[] strs = new String[]{"car","cir"};
//        System.out.println(longestCommonPrefix(strs));
//    }
}
